package cqrtplm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import cqrtplm.entity.ObjectStorageDO;
import cqrtplm.mapper.ObjectStorageMapper;
import cqrtplm.service.ObjectStorageService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;

@Service
public class ObjectStorageServiceImpl implements ObjectStorageService {

    @Resource
    private ObjectStorageMapper objectStorageMapper;

    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;

    @Override
    public ObjectStorageDO selectOneByTypeDefName(String name) {
        return objectStorageMapper.selectOneByTypeDefName(name);
    }

    @Override
    public void saveObjectStorage(ObjectStorageDO objectStorage) {
        ObjectStorageDO objectStorageDO = objectStorageMapper.selectOneByTypeDefName(objectStorage.getTypedefName());
        if (objectStorageDO != null){
            throw new RuntimeException("类型名称已经存在，请重新新建");
        }
        if (StrUtil.isBlank(objectStorage.getFolderPath())){
            throw new RuntimeException("存储路径不能为空！");
        }
        if (!objectStorage.getFolderPath().substring(0,1).equals("/")){
            throw new RuntimeException("存储路径必须以 '/' 开始!");
        }
        objectStorage.setOid(snowflakeIdComponent.getInstance().nextId().toString());
        if (objectStorage.getTypename().equals("零部件")){
            objectStorage.setObjectOType("ty.inteplm.part.CTyPart");
        }else if (objectStorage.getTypename().equals("文档")){
            objectStorage.setObjectOType("ty.inteplm.doc.CTyDoc");
        }else if (objectStorage.getTypename().equals("表单")){
            objectStorage.setObjectOType("ty.inteplm.form.CTyFormData");
        }else if (objectStorage.getTypename().equals("CAD文档")){
            objectStorage.setObjectOType("ty.inteplm.cad.CTyCADDoc");
        } else {
            throw new RuntimeException("错误的类型:"+objectStorage.getTypename());
        }
        objectStorageMapper.saveObjectStorage(objectStorage);
    }

    @Override
    public PageInfo selectAll(int pageNum, int pageSize, String defName) {
        PageHelper.startPage(pageNum,pageSize);
        List<ObjectStorageDO> list = objectStorageMapper.selectAll(defName);
        PageInfo<ObjectStorageDO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void updateObjectStorage(ObjectStorageDO objectStorageDO) {
        if (StrUtil.isBlank(objectStorageDO.getOid())){
            throw new RuntimeException("oid不能为空");
        }
        objectStorageMapper.updateObjectStorage(objectStorageDO);
    }

    @Override
    public String selectTypeDisplayNameByTypeId(BigInteger typeId) {
        return objectStorageMapper.selectTypeDisplayNameByTypeId(typeId);
    }
}
